package org.genntii.smgateway.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.genntii.smdomain.entity.User;
import org.genntii.smgateway.domain.entity.LoginUser;
import org.genntii.smgateway.mapper.RoleMapper;
import org.genntii.smgateway.mapper.UserMapper;
import org.genntii.smgateway.mapper.UserRoleMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class DBUserDetailsManager implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            throw new UsernameNotFoundException(username);
        }else {

            ArrayList<Long> rolesIdArray = userRoleMapper.selectByUserId(user.getId());

            ArrayList<String> roleNameArray = new ArrayList<>();

            rolesIdArray.forEach(item -> roleNameArray.add(roleMapper.selectByRoleId(item)));
            String[] roles = roleNameArray.toArray(new String[0]);

            return new LoginUser(user,roles);
        }
    }
}
